<template>
  <div
    v-loading="isLoading"
    class="panel-property"
  >
    <div class="content">
      <PanelLabelOverflowTooltip
        ref="panelLabelOverflowTooltip"
        :component-style="form.componentStyle"
      />
      <el-form
        ref="form"
        v-panel-label-overflow-tooltip="getPanelLabelOverflowTooltip()"
        class="prop-form"
        label-position="right"
        :model="form"
        :rules="rules"
        label-width="30%"
      >
        <BaseOption
          v-if="isIcon"
          :form="form"
          option="multiSortBy"
        />
        <VsFormItem
          v-if="!isIcon"
          :label="$demoi18n('word.indicators')"
        >
          <Range
            v-model:value="count"
            type="input"
            :min="minLen"
            :max="maxLen"
          />
        </VsFormItem>
        <VsFormItem
          v-if="!isIcon"
          prop="unit"
          :label="$demoi18n('word.unit')"
        >
          <el-input
            v-model="form.unit"
            :placeholder="$demoi18n('placeholder.enterUnit')"
            size="default"
            style="width:90%;"
          ></el-input>
        </VsFormItem>
        <VsFormItem
          v-if="!isIcon"
          label="Tooltip"
        >
          <BaseOption
            :form="form"
            option="tooltip"
            :widget-instance-id="widgetInstanceId"
            :config="config"
          />
        </VsFormItem>
        <div
          v-if="isIcon"
          class="config-table"
        >
          <div class="top-btns">
            <el-button
              class="btn-sure"
              size="default"
              icon="CirclePlus"
              :disabled="addDisable"
              @click.stop="addNewRow(temp, item, 'data')"
            >
              {{ $demoi18n('btn.add') }}
            </el-button>
            <BaseOption
              :form="form"
              option="tooltip"
              :widget-instance-id="widgetInstanceId"
              :config="config"
            />
          </div>
          <el-table
            class="config-panel-table mapping-table"
            :data="form.data"
            :row-style="{ height: '25px' }"
            :header-row-style="{ height: '25px' }"
            max-height="235"
            :header-cell-style="{ lineHeight: '15px' }"
          >
            <el-table-column
              type="index"
              :label="$demoi18n('word.serialNumber')"
              :width="35"
            ></el-table-column>
            <el-table-column
              prop="name"
              :label="$demoi18n('word.name')"
              :min-width="110"
            >
              <template #default="scope">
                <VsFormItem
                  :prop="`data[${scope.$index}].name`"
                  :rules="
                    generateRules({
                      required: false,
                    })
                  "
                >
                  <ValueInputer
                    v-model:value="scope.row.name"
                    :enum-values="nameListSeries"
                  />
                </VsFormItem>
              </template>
            </el-table-column>
            <el-table-column
              prop="name"
              :label="$demoi18n('panel.th.aliasName')"
              :min-width="110"
            >
              <template #default="scope">
                <VsFormItem
                  :prop="`data[${scope.$index}].alias`"
                  :rules="
                    generateRules({
                      required: false,
                    })
                  "
                >
                  <el-input
                    v-model="scope.row.alias"
                    size="default"
                  ></el-input>
                </VsFormItem>
              </template>
            </el-table-column>
            <el-table-column
              prop="unit"
              :label="$demoi18n('word.unit')"
              :min-width="110"
            >
              <template #default="scope">
                <VsFormItem
                  :prop="`data[${scope.$index}].unit`"
                  :rules="
                    generateRules({
                      required: false,
                    })
                  "
                >
                  <el-input
                    v-model="scope.row.unit"
                    size="default"
                  ></el-input>
                </VsFormItem>
              </template>
            </el-table-column>
            <el-table-column
              v-if="isIcon"
              prop="icon"
              :label="$demoi18n('word.icon')"
              width="45"
            >
              <template #default="scope">
                <IconEditor
                  :icon="scope.row.icon"
                  :component-style="form.componentStyle"
                  :has-sync="true"
                  @save="saveIcon($event, scope.row)"
                  @delete="deleteIcon($event, scope.row)"
                  @sync="syncIcons($event, form.data)"
                />
              </template>
            </el-table-column>
            <el-table-column width="30">
              <template #default="scope">
                <el-button
                  icon="Delete"
                  :link="true"
                  type="primary"
                  :disabled="delDisable"
                  @click.stop="deleteCurRow(scope.row, 'data')"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 阈值区间 目前双排和单排带图标可显示 -->
        <VsFormItem :label="$demoi18n('word.threshold')">
          <el-button
            type="primary"
            class="btn-sure"
            size="default"
            @click="openThreshod"
          >
            {{ $demoi18n('btn.thresholdSetting') }}
          </el-button>
        </VsFormItem>
        <VsFormItem
          v-if="!isSingleLine"
          :label="$demoi18n('panel.label.arrangement')"
          prop="layoutZN"
        >
          <el-radio-group v-model="form.layoutZN">
            <el-radio label="N">{{ $demoi18n('panel.option.NShaped') }}</el-radio>
            <el-radio label="Z">{{ $demoi18n('panel.option.ZShaped') }}</el-radio>
          </el-radio-group>
        </VsFormItem>
        <VsFormItem :label="$demoi18n('panel.label.dynamicAdaptation')">
          <el-switch v-model="form.isDynamicAdapt"></el-switch>
        </VsFormItem>
        <VsFormItem
          :label="$demoi18n('panel.label.showSelectedStatus')"
          label-width="110px"
        >
          <el-switch v-model="form.selectedStatus"></el-switch>
        </VsFormItem>

        <VsFormItem
          v-if="isTextComposition"
          :prop="option"
          :label="$demoi18n('label.typesetting')"
        >
          <el-radio-group
            v-model="form.textComposition"
            size="default"
          >
            <el-radio label="horizontal">{{ $demoi18n('base-option.nameOnTop') }}</el-radio>
            <el-radio label="vertical">{{ $demoi18n('base-option.nameOnBottom') }}</el-radio>
          </el-radio-group>
        </VsFormItem>

        <VsFormItem :label="$demoi18n('word.singleValueSpace')">
          <Range
            v-model:value="form.unitGap"
            :min="0"
            :max="1000"
            type="input"
          />
        </VsFormItem>
        <OptionCollapse>
          <el-collapse-item
            :title="$demoi18n('echart.setting.component')"
            name="cssStyle.grid"
          >
            <BaseOption
              :form="form"
              option="cssStyle.grid"
              :df-css-style-attrs="dfCssStyleAttrs.grid"
            />
            <VsFormItem
              :label="$demoi18n('panel.cssStyle.bgColor')"
              class="range-content"
            >
              <ColorPicker v-model:value="form.backgroundColor" />
            </VsFormItem>
          </el-collapse-item>
          <el-collapse-item
            :title="$demoi18n('panel.label.titleStyle')"
            name="cssStyle.title"
          >
            <BaseOption
              :form="form"
              option="title"
            />
            <BaseOption
              :form="form"
              option="cssStyle.title"
              :df-css-style-attrs="dfCssStyleAttrs.title"
            />
            <BaseOption :form="form" option="isTitleSignVisiable" />
            <BaseOption v-if="form.isTitleSignVisiable" :form="form" option="signMarginLeft" />
            <BaseOption v-if="form.isTitleSignVisiable" :form="form" option="verticalLineBackgroundColor" />
          </el-collapse-item>
          <el-collapse-item
            :title="$demoi18n('word.name')"
            name="cssStyle.name"
          >
            <BaseOption
              :form="form"
              option="cssStyle.name"
              :df-css-style-attrs="dfCssStyleAttrs.name"
            />
          </el-collapse-item>
          <el-collapse-item
            :title="$demoi18n('word.numValue')"
            name="cssStyle.value"
          >
            <BaseOption
              :form="form"
              option="cssStyle.value"
              :df-css-style-attrs="dfCssStyleAttrs.value"
            />
          </el-collapse-item>
          <el-collapse-item
            :title="$demoi18n('word.unit')"
            name="cssStyle.unit"
          >
            <BaseOption
              :form="form"
              option="cssStyle.unit"
              :df-css-style-attrs="dfCssStyleAttrs.unit"
            />
          </el-collapse-item>
          <BaseOption
            :form="form"
            option="noDataPromptSetting"
          />
        </OptionCollapse>
        <BaseOption
          :form="form"
          option="componentStyle"
          @change="onComponentStyleChange"
        />
        <AdvanceSet :form="form"></AdvanceSet>
      </el-form>
    </div>

    <ThresholdSetting
      ref="thresholdSetting"
      :form="form"
      :is-icon="isIcon"
      :config="config"
      :upload-img-list="uploadImgList"
      :active-color-switch="activeColorSwitch"
      :active-color-radio="activeColorRadio"
      :name-list="nameList"
      @save="handleThresholdSave"
    />
    <PanelPropertyBottom :config="config" :widgetInstanceId="widgetInstanceId" :form="form" />
  </div>
</template>
<script>
import AdvanceSet from '@/components/common/advance-setting/advance-setting.vue';
import OptionCollapse from '@/components/common/base-option/option-collapse/option-collapse.vue';
import ColorPicker from '@/components/common/color-picker/color-picker.vue';
import IconEditor from '@/components/common/icon/icon-editor.vue';
import PanelLabelOverflowTooltip from '@/components/common/overflow-tooltip/overflow-tooltip.vue';
import Range from '@/components/common/range/range.vue';
import ThresholdSetting from '@/components/common/threshold-setting/threshold-setting';
import ValueInputer from '@/components/common/value-inputer/value-inputer.vue';
import imgUploadBase from '@/mixin/img-upload-base.js';
import panelPropertyBase from '@/mixin/panel-property-base.js';
import { colorRGB2Hex, numFormat } from '@/utils/util';
import BaseOption from '../common/base-option/base-option.vue';
import colorGroup from './colorGroup.js';
import dfCssStyleAttrs from './cssStyle-default.js';
import EventBus from '@/event-bus/EventBus.js';
export default {
  name: 'PanelProperty',
  components: {
    Range,
    BaseOption,
    ValueInputer,
    OptionCollapse,
    ColorPicker,
    ThresholdSetting,
    IconEditor,
    PanelLabelOverflowTooltip,
    AdvanceSet,
  },
  mixins: [imgUploadBase, panelPropertyBase],
  props: ['config', 'widgetInstanceId', 'widget', 'minLen', 'maxLen'],
  data() {
    return {
      activeColorRadio: '#2D8CF0', // 单选框选中时的颜色
      colorGroup: colorGroup,
      isLoading: false,
      countOptions: [],
      form: {
        imgSize: 60,
      },
      item: {
        name: '',
        alias: '',
        unit: '',
        icon: '',
        iconSmall: '',
        uploadList: '',
        imgUrl: '',
      },
      temp: {},
      delDisable: true,
      addDisable: false,
      isIcon: false,
      isSingleLine: false,
      isTextComposition: false,
      nameList: [],
      nameListSeries: [],
      dfCssStyleAttrs: {},
    };
  },
  computed: {

    // 将无图标的count配置项转化为this.form.data.length值，与带图标的组件逻辑统一
    count: {
      get() {
        return this.form.data.length;
      },
      set(v) {
        this.form.data = [];
        const count = v;
        for (let i = 0; i < count; i++) {
          this.temp = JSON.parse(JSON.stringify(this.item));
          this.form.data.push(this.temp);
        }
      },
    },
  },
  watch: {
    'form.data': {
      handler() {
        this.checkLimit();
      },
      deep: true,
    },
  },
  created() {
    // 读取配置
    if (this.config) {
      const form = JSON.parse(JSON.stringify(this.config.config.property));
      if (!form.imgSize) {
        form.imgSize = 60;
      }
      this.form = form;

      // 初始化配置数据
      this.initMultiConfigData();
      this.initDfCssStyleAttrs();
    }

    EventBus.$on(`apiDataChanged_${this.widgetInstanceId}`, this.apiDataChanged);
  },
  methods: {
    getPanelLabelOverflowTooltip() {
      return {
        parentComp: this,
      };
    },
    initDfCssStyleAttrs() {
      this.dfCssStyleAttrs = dfCssStyleAttrs;
    },
    initMultiConfigData() {
      if (!this.form.threshold || this.form.threshold.length === 0) {
        this.form.threshold = [
          {
            min: 0,
            max: 0,
            text: '',
            color: '',
            icon: '',
            iconSmall: '',
            uploadList: '',
            imgUrl: '',
          },
        ];
      }
      this.form.threshold.forEach(item => {
        item.color = colorRGB2Hex(item.color);
      });
      const { count } = this;
      for (let i = count; i < this.minLen; i++) {
        this.temp = JSON.parse(JSON.stringify(this.item));
        this.form.data.push(this.temp);
      }
      this.form.thresholdDataType = this.form.thresholdDataType || 'number';

      this.delDisable = this.count <= this.minLen;
      this.addDisable = this.count >= this.maxLen;
      this.isIcon = this.form.propertyGroup.indexOf('Icon') > -1;
      this.isSingleLine = this.form.propertyGroup.indexOf('Single') > -1;

      // 两行不带图标有排版功能
      this.isTextComposition = !this.isIcon && !this.isSingleLine;
      this.initCountOptions();
    },
    initCountOptions() {
      for (let i = this.minLen; i <= this.maxLen; i++) {
        this.countOptions.push({
          value: i,
        });
      }
    },
    addNewRow(temp, item, group) {
      const _temp = JSON.parse(JSON.stringify(item));
      this.form[group].push(_temp);
      if (this.count >= this.minLen) {
        this.delDisable = false;
      }
      if (this.count >= this.maxLen) {
        this.addDisable = true;
      }
    },
    deleteCurRow(item, group) {
      const index = this.form[group].indexOf(item);
      this.form[group].splice(index, 1);
      if (this.count <= this.minLen) {
        this.delDisable = true;
      }
      if (this.count <= this.maxLen) {
        this.addDisable = false;
      }
    },
    onComponentStyleChange() {
      const { title, name, value, unit } = this.form.cssStyle;
      if (title) {
        title.backgroundColor = this.getValByCompStl('#fff', '#0D263A', '#232323');
        title.color = this.getValByCompStl('#3c3c3c', '#00f7ff', '#eee');
      }
      if (name) {
        name.color = this.getValByCompStl('#333333', '#ffffff', '#eee');
      }
      if (value) {
        value.color = this.getValByCompStl('#2d8cf0', '#2df7ff', '#eee');
      }
      if (unit) {
        unit.color = this.getValByCompStl('#2d8cf0', '#2df7ff', '#eee');
      }
      this.form.backgroundColor = this.getValByCompStl('#ffffff', '#0D263A', '#232323');
    },
    openThreshod() {
      if (this.$refs.thresholdSetting) {
        this.$refs.thresholdSetting.openDialog();
      }
    },
    handleThresholdSave(thresholdForm) {
      const { isThreshold, thresholdData, thresholdDataType } = thresholdForm;
      this.form = {
        ...this.form,
        isThreshold,
        threshold: thresholdData,
        thresholdDataType,
      };
    },
    handleCount() {
      this.form.data = [];
      const { count } = this;
      for (let i = 0; i < count; i++) {
        this.temp = JSON.parse(JSON.stringify(this.item));
        this.form.data.push(this.temp);
      }
    },
    checkLimit() {
      const { data } = this.form;
      const nameList = data.map(n => n.name).filter(n => n);
      const aliasList = data.map(n => n.alias).filter(n => n);
      const nameListU = Array.from(new Set(nameList));
      const aliasListU = Array.from(new Set(aliasList));
      if (nameList.length !== nameListU.length || aliasList.length !== aliasListU.length) {
        this.$message.error(this.$demoi18n('message.nameOrAliasRepeated'));
        return false;
      }
      return true;
    },
    apiDataChanged(apiData) {
      if (!apiData) {
        this.nameList = [];
        this.nameListSeries = [];
      } else {
        const arr = apiData.map(n => {
          if (n.y) {
            n.y = numFormat(n.y, true);
            n.y = n.y.toString();
          }
          return n.y;
        });
        this.nameList = Array.from(new Set(arr));
        const arrSeries = apiData.map(n => {
          if (n.s) {
            n.s = n.s.toString();
          }
          return n.s;
        });
        this.nameListSeries = Array.from(new Set(arrSeries));
      }
    },
  },
};
</script>

<style lang="less">
@import '../../common/color-picker-panel.less';
</style>
<style lang="less" scoped>
@import '../common/overflow-tooltip/el-form-item-label-tooltip.less';
</style>
<style lang="less" scoped>
.panel-property {
  .content {
    .prop-form {
      padding: 0 10px;

      .slider-number {
        vertical-align: text-bottom;
        padding-right: 5px;
      }

      .slider-number-left {
        vertical-align: text-bottom;
        padding-right: 15px;
      }
      .slider-number-right {
        vertical-align: text-bottom;
        padding-left: 15px;
      }
      :deep(.el-slider) {
        display: inline-block;
        width: 100px;
      }

      :deep(.el-select) {
        .el-input__inner {
          width: 100%;
        }
      }

      .config-table {
        :deep(.el-table__row > td) {
          border: none;
        }
        :deep(.el-table) {
          .cell {
            padding: 0 3px !important;
            .el-input__inner {
              padding: 0 5px !important;
            }
          }
          td,
          th {
            padding: 5px 0 !important;
          }
          :deep(.el-table__row) {
            .el-table_1_column_4,
            .el-table_2_column_6,
            .el-table_2_column_7,
            .el-table_2_column_8 {
              .cell {
                display: flex;
                align-items: center;
                justify-content: center;
              }
            }
          }
        }
      }

      :deep(.el-form-item) {
        margin-bottom: 0;
        .el-form-item__label {
          min-width: 80px;
        }
      }
      .range-content {
        :deep(.el-form-item__content) {
          display: flex;
          min-height: 40px;
          align-items: center;
        }
      }
      .input-number {
        width: 80px;
        :deep(.el-input-number__decrease) {
          width: 19px;
          background-color: #fff;
        }
        :deep(.el-input-number__increase) {
          width: 19px;
          background-color: #fff;
        }
        :deep(.el-input__inner) {
          padding-left: 19px;
          padding-right: 19px;
        }
      }
      .input-number-left {
        margin-right: 25px;
      }

      .color-radio-group {
        background-color: #eeeeee;
        :deep(.el-radio-button__inner) {
          display: inline-block;
          padding: 2px 2px;
          border: 0;
          border-radius: 0;
          height: 24px;
          margin: 2px 2px;
          background: #eeeeee;
        }
        :deep(.is-active) {
          .el-radio-button__inner {
            background-color: #409eff;
          }
        }
      }
      .top-btns {
        .base-option {
          display: inline-block;
          margin-left: 10px;
        }
      }
    }
  }
}
</style>

<style lang="less" scoped>
@import './panel-property.less';
</style>
